package com.blog.dao.impl;

import com.blog.dao.UserDao;
import com.blog.entity.User;
import com.blog.util.DBUtil;

import java.sql.*;
import java.util.Date;

public class UserDaoImpl implements UserDao {

    @Override
    public User findByUsername(String username) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;

        try {
            // 获取数据库连接
            conn = DBUtil.getConnection();

            // SQL语句（使用?占位符防止SQL注入）
            String sql = "SELECT * FROM user WHERE username = ?";

            // 创建预处理语句对象
            pstmt = conn.prepareStatement(sql);

            // 设置参数（第一个参数是占位符索引，从1开始）
            pstmt.setString(1, username);

            // 执行查询，返回结果集
            rs = pstmt.executeQuery();

            // 处理结果集
            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setNickname(rs.getString("nickname"));
                user.setAvatar(rs.getString("avatar"));
                user.setCreatedTime(rs.getTimestamp("created_time"));
                user.setLastLoginTime(rs.getTimestamp("last_login_time"));
            }
        } catch (SQLException e) {
            System.err.println("查询用户失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭资源（注意顺序：ResultSet -> PreparedStatement -> Connection）
            DBUtil.close(conn, pstmt, rs);
        }
        return user;
    }

    public static void main(String[] args) {
        UserDaoImpl userDao = new UserDaoImpl();
        System.out.println(userDao.findByUsername("root"));
    }
    @Override
    public User findById(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        User user = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);

            rs = pstmt.executeQuery();

            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setNickname(rs.getString("nickname"));
                user.setAvatar(rs.getString("avatar"));
                user.setCreatedTime(rs.getTimestamp("created_time"));
                user.setLastLoginTime(rs.getTimestamp("last_login_time"));
            }
        } catch (SQLException e) {
            System.err.println("根据ID查询用户失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt, rs);
        }

        return user;
    }

    @Override
    public int add(User user) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int rows = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO user(username, password, nickname, avatar, created_time) " +
                    "VALUES (?, ?, ?, ?, ?)";

            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getNickname());

            // 处理头像字段，允许为空
            if (user.getAvatar() != null) {
                pstmt.setString(4, user.getAvatar());
            } else {
                pstmt.setNull(4, java.sql.Types.VARCHAR);
            }

            pstmt.setTimestamp(5, new java.sql.Timestamp(new Date().getTime()));

            rows = pstmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println("添加用户失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt);
        }

        return rows;
    }

    @Override
    public int updateLastLoginTime(int id) {
        Connection conn = null;
        PreparedStatement pstmt = null;
        int rows = 0;

        try {
            conn = DBUtil.getConnection();
            String sql = "UPDATE user SET last_login_time = ? WHERE id = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setTimestamp(1, new java.sql.Timestamp(new Date().getTime()));
            pstmt.setInt(2, id);

            // 执行更新，返回受影响的行数
            rows = pstmt.executeUpdate();
        } catch (SQLException e) {
            System.err.println("更新登录时间失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pstmt);
        }

        return rows;
    }
}